package 调度执行顺序;

/**
 * Created with IntelliJ IDEA.
 * Description:synchronized如果是要修饰代码块,必须在方法里面
 * wait和notify必须是针对同一个对象
 * User: lenovo
 * Date: 2022-09-24
 * Time: 21:58
 */
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
      Object object = new Object();
      //第一个线程进行wait操作
        Thread t1 = new Thread(){
            @Override
            public void run() {
               while (true){
                   synchronized (object){
                       try {
                           System.out.println("这是wait执行前");
                           object.wait();//这里会将锁释放
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                       System.out.println("这是wait执行后");
                   }
               }
            }
        };
        t1.start();
        //第二个线程,进行notify
        Thread t2 = new Thread(){
            @Override
            public void run() {
              while (true){
                  synchronized (object){//wait释放锁后,这里会拿到锁
                      System.out.println("这是notify执行前");
                      object.notify();//notify之后不会立即释放锁,还得进行一些操作才会将锁释放,wait才能在一次拿到锁
                      System.out.println("这是notify执行后");
                  }
                  try {
                      Thread.sleep(10000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
            }
        };
        t2.start();

    }
}
